var $productDetailTable = $('#productDetailTable');//产品详情Table
var $activityProductTable = $('#activityProductTable');//活动产品Table
var $giftDetailTable = $('#giftDetailTable');//赠品详情Table
var $findAudit = $('#findAudit');//审核结果Table
// 合同附件
var annexFilePath;
// 审核附件
var examineFilePath;

var contractId =$("#contractId").val();//合同ID
var orderId = $("#orderId").val();//订单ID
var clueFollowId,opportunityIds;//跟进id,商机id
var pageIndex=1,pageSize=5,totalNum;//当前商机动态分页索引初始化为1,//商机动态每次加载5条,//商机动态总数据量
var membershipStartTm='',membershipExpirationTm='';
/**
 * 初始化
 */
$(function () {
    // timeData('startAndEndDate','startAndEndDate','editContractForm');//合同编辑--合同起止日期配置

    contractId = $("#contractId").val();//合同ID
    orderId = $("#orderId").val();//订单ID

    //初始化合同详情&订单详情
    initContractData();
    //初始化产品详情
    productDetailTableListInit();
    //初始化活动产品
    activityProductTableInit();
    //初始化赠品详情
    giftDetailTableInit();
    //初始化审核结果
    findAuditTableInit();
    //初始化优惠卷
    couponTableInit();

    //拖拽add
    var times = 0;
    var x_left = '',y_top = '';
    $('#model-add-mousedown').mousedown(function(e){
        times++;

        var positionDiv = $(this).offset();
        var distenceX = e.pageX - positionDiv.left;
        var distenceY = e.pageY - positionDiv.top;

        if(times==1){
            x_left=positionDiv.left;
            y_top=positionDiv.top
        }

        $(document).mousemove(function(e){
            var x = e.pageX - distenceX;
            var y = e.pageY - distenceY;
            if(x<0){
                x=0;
            }else if(x>$(document).width()-$('#model-add-mousedown').outerWidth(true)){
                x = $(document).width()-$('#model-add-mousedown').outerWidth(true);
            }
            if(y<0){
                y=0;
            }else if(y>$(document).height()-$('#model-add-mousedown').outerHeight(true)){
                y = $(document).height()-$('#model-add-mousedown').outerHeight(true);
            }

            $('#model-add-mousedown').css({
                'left':x-x_left+'px',
                'top':y-y_top+'px'
            });
        });
        $(document).mouseup(function(){
            $(document).off('mousemove');

        });
    });



});

function TelCall(){
    // var tel='tel://'+'18811355753'
    // var tel='tel://'+$('#contactDetails').html()
    // $("#tel-dial").attr("href",tel)
}

/**
 * 初始化合同详情&订单详情数据
 */
function initContractData() {
    $.ajax({    // 获取活动相关产品
        type: "get",
        url: "/contractReview/getContractReviewDetail?contractId=" + contractId,
        async: false,
        success: function (data, status) {
            if(data.code == '000000') {
                clueFollowId = data.data.followRecordId;//跟进id
                opportunityIds = data.data.opportunityId;//商机id
                if(clueFollowId === null && opportunityIds === null){
                    $("#followBtnCon").hide();
                }else if(clueFollowId === null){
                    $("#followUpDetail .followInfoContainer").hide();
                }else if(opportunityIds === null){
                    $("#followUpDetail .businessDynamics").hide();
                }
                // 合同附件URL
                annexFilePath = data.data.contractAnnexAccessUrl;
                // 审核附件RUL
                examineFilePath = data.data.reviewAnnexAccessUrl;
                // 判断是否存在附件
                if (annexFilePath) {
                    $('.annex-group').show();
                    $('.annex-group button').prop('disabled', false);
                }
                if (examineFilePath) {
                    $('.approval').show();
                    $('.approval button').prop('disabled', false);
                    $('#contractReviewNotes').html(data.data.contractReviewNotes);
                }

                $('#contractType').html(data.data.contractTypeText);//合同类型
                $('#contractStatus').html(data.data.contractStatusText);
                $('#contractNumber').html(data.data.contractNumber);//合同编号
                $('#customerName').html(data.data.customerName);//客户名称
                $('#customerId').val(data.data.customerId);//客户ID(客户名跳转客户详情用)
                $('#customerType').html(data.data.customerType);//客户类型(客户名跳转客户详情用)
                $('#contactName').html(data.data.contactName);//客户联系人
                var dataTel = data.data.contactDetails;//联系方式
                if(dataTel != null){
                    $('#contactDetails').html(dataTel.slice(0,3)+'-'+dataTel.slice(3,7)+'-'+dataTel.slice(7));
                }

                $('#customerEmail').html(data.data.customerEmail);//客户邮箱
                $('#createPeopleName').html(data.data.createPeopleName);//创建人
                $('#createTm').html(data.data.createTm);//创建时间
                $('#payBackDate').html(data.data.payBackDate);//到款时间
                $('#followRecordName').html(data.data.followRecordName);
                $('#masterMembershipContract').html(data.data.masterMembershipContract);//会员主合同编号
                $('#masterMembershipContractId').val(data.data.masterMembershipContractId);//会员主合同ID
                $('#remark').html(data.data.contractReviewNotes);//备注
                if(!data.data.masterMembershipContractStartTime && !data.data.masterMembershipContractEndTime){//主会员合同起止日期
                    $('#masterMembershipContractStartEndTime').html("-- 至 --");
                }else{
                    $('#masterMembershipContractStartEndTime').html(data.data.masterMembershipContractStartTime+ ' 至 ' + data.data.masterMembershipContractEndTime)
                }
                //-----------给会员主合同产品表格赋值------------------
                setMasterMembershipContractProductList(data.data.productOrderDetailList);
                $('#opportunityName').html(data.data.opportunityName);
                $('#opportunityId').html(data.data.opportunityId);
                $('#advancePostponementReason').html(data.data.advancePostponementReason);//提前/延期原因
                if(!data.data.contractStartDate && !data.data.contractEndDate){
                    var contractDatetime = '-- 至 --'
                }else{
                    var contractDatetime = data.data.contractStartDate+' 至 '+ data.data.contractEndDate;
                }
                $("#contractDate").html(contractDatetime);//合同起止日期
                $('#orderSurcharge').html(data.data.orderSurcharge);//附加费用金额
                $('#orderSurchargeRemark').html(data.data.orderSurchargeRemark);//附加费用备注
                if ($('#orderSurcharge').html() == '' || $('#orderSurcharge').html() == '0') {
                    $('.surcharge-remarks').hide();
                } else {
                    $('.surcharge-remarks').show();
                }
                // 合计金额
                $('#contractTotalAmount').html(data.data.contractTotalAmount);//合同总金额
                $('#contractDiscountTotalAmount').html(data.data.contractDiscountTotalAmount);//合同优惠总金额
                $('#contractReceivables').html(data.data.contractReceivables);//合同应收款
                $('#contractActualTotalAmount').html(data.data.contractActualTotalAmount);//合同实际总金额

                //订单详情
                $('#orderNumber').html(data.data.orderNumber);//订单编号
                $('#orderStatus').html(data.data.orderStatus);//订单状态
            }
        }
    });
}

/**
 * --列表序列号
 */
function indexFormat(value, row, index) {
    return index + 1;
}

/**
 * 合同详情-主合同产品
 **/
function setMasterMembershipContractProductList(dataList){
    //先销毁表格
    $('#masterContractProduct').bootstrapTable('destroy');
    $('#masterContractProduct').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        undefinedText: '-',//cell没有值时显示
        // 判断dataList是否为null
        data: dataList || {},
        columns: [
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '产品名称',field: 'orderDetailName', align: 'left', valign: 'middle'},
            {title: '成交价格', field: 'productFinalPrice',align: 'left', valign: 'middle'}
        ]
    });
}

/**
 * 合同详情--客户名称点击
 */
$("#customerName").click(function(){
    //客户id
    var customerId = $("#customerId").val();
    //客户类型
    var customerType = $("#customerType").val();
    //客户名称
    var customerName = $("#customerNameRepeat").val();
    //联系方式
    var contactDetails = $('#contactDetails').val().replace('-','');
    //跳转
    if(customerType == 1){//个人客户
        contactNameDetail(customerName,contactDetails,customerId);
    }else if(customerType == 0){//企业客户
        customerDetail(customerId);
    }
});

/**
 * 合同详情--客户名称点击跳转((个人客户))
 * @param customerName
 * @param contactPersonPhone
 */
function contactNameDetail (customerName, contactPersonPhone, customerId) {
    var contactId = "";
    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getCustomerIdAndContactNameAndAccountId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId,
            contactName: customerName,
            contactInformation : contactPersonPhone,
            contactNature : '1',
            csd : 'csd'
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }else{
                    $.alert("数据有问题,请重试!");
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });
}

/**
 * 合同详情--客户名称点击跳转((企业客户))
 * @param customerId
 */
function customerDetail (customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '客户详情',
        url : "/front/user/customerManager/customerDetail?customerId=" + customerId + "&csd=csd"
    }, true);
}

/**
 * 合同详情--主会员合同跳转
 */
$("#masterMembershipContract").click(function(){
    //主会员合同id
    var masterMembershipContractId = $("#masterMembershipContractId").val();//主会员合同ID
    parent.$(parent.document).data('multitabs').create({
        iframe : true,
        title : '合同详情',
        url : "/front/contractManager/contractDetail?contractId=" + masterMembershipContractId
    }, true);
});

/**
 * 产品详情--分页列表页
 */
function productDetailTableListInit() {
    //先销毁表格
    $productDetailTable.bootstrapTable('destroy');
    $productDetailTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/selectCustomerProductOrderDetailList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderDetailId',
        idField: 'orderRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId:orderId,// $('#productOrderId').val(),
                productOrderDetailType: '1'
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80',formatter: indexFormat},
            {title: '产品名称', field: 'orderDetailName', align: 'left', valign: 'middle', class: 'ellipsis'},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'},
            {title: '产品会员价', field: 'productMemberPrice', align: 'left', valign: 'middle'},
            {title: '产品成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '产品数量', field: 'productQuantity', align: 'left', valign: 'middle'},
            {title: '产品优惠金额', field: 'productPreferentialPrice', align: 'left', valign: 'middle',
                formatter: function (value, row) {
                    if (value < 0) {
                        return 0;
                    } else {
                        return value * row.productQuantity;
                    }
                }
            }
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
        },
    });
}

/**
 * 活动产品 --分页列表页
 */
function activityProductTableInit() {
    //先销毁表格
    $activityProductTable.bootstrapTable('destroy');
    $activityProductTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order/selectCustomerProductOrderDetailList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'productOrderDetailId',
        idField: 'orderRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId: orderId, //$('#productOrderId').val()
                productOrderDetailType: '2'
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '活动名称', field: 'orderDetailName', align: 'left', valign: 'middle'},
            {title: '活动原价',field: 'productOriginalPrice', align: 'left',valign: 'middle'},
            {title: '活动成交价', field: 'productFinalPrice', align: 'left', valign: 'middle'},
            {title: '产品数量',field: 'productQuantity', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#activityProductTable').css({
                minWidth: $('#activityProductTable').width()
            })
        },
        detailView: true,
        detailFormatter: function(index,row){
            var html = '';
            var productOrderId =orderId;
            $.ajax({    // 获取活动相关产品
                type: "post",
                url: "/order/selectCustomerOrderActivityRelationById",
                data: {
                    productOrderId: productOrderId,
                    orderRelationId: row.orderRelationId
                },
                dataType: 'json',
                async: false,
                success: function (data, status) {
                    if(data.code == '000000') {
                        var customerProductList = data.data;
                        if(customerProductList){
                            for (var i = 0; i < customerProductList.length; i++) {
                                html += '<span class="label label-info">' + customerProductList[i].productName + '</span>';
                            }
                        }
                    }
                }
            });
            return html;
        },
        onPostBody(data) {
            $('#activityProductTable').bootstrapTable('expandAllRows');     // 展开所有行
        }
    });
}

/**
 * 赠品详情--分页列表页
 */
function giftDetailTableInit() {
    //先销毁表格
    $giftDetailTable.bootstrapTable('destroy');
    $giftDetailTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/order//selectCustomerOrderGiftRelationList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                productOrderId: orderId, //$('#productOrderId').val()
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'orderGiftRelationId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '产品名称', field: 'productGiftName', align: 'left', valign: 'middle',},
            {title: '产品原价', field: 'productOriginalPrice', align: 'left', valign: 'middle'},
            {title: '产品单价', field: 'productUnitPrice', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            $('.JCLRgrips').remove();
            $('#giftDetailTable').css({
                minWidth: $('#giftDetailTable').width()
            })
        },
    });
}

/**
 * 优惠券--分页列表页
 */
function couponTableInit() {
    //先销毁表格
    $('#couponTable').bootstrapTable('destroy');
    $('#couponTable').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/contractCoupon/selectContractCouponByContractId?contractId='+contractId+'',//请求地址
        method: 'get',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        columns: [
            {title: '主键', field: 'chsCustomerCouponId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '60', formatter: indexFormat},
            {title: '优惠券名称',field: 'couponName', align: 'left', valign: 'middle'},
            {title: '优惠券类型', field: 'couponType',align: 'left', valign: 'middle', formatter: couponFormat.couponType},
            {title: '优惠券额度', field: 'couponQuota',align: 'left', valign: 'middle'},
            {title: '优惠券优惠折扣', field: 'couponDiscount',align: 'left', valign: 'middle'},
        ],
        responseHandler: function (result) {
            console.log(result);
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                };
            } else {
                var obj = {
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
        },
    });
}

/**
 * 优惠券列表--自定义优惠券类型
 */
var couponFormat = {
    couponType: function (value, row, index, field) {
        if (value == '1') {
            return '折扣类'
        } else if(value == '2'){
            return '额度类'
        }else{
            return '';
        }
    },
};

/**
 * 审核结果--分页列表页
 */
function findAuditTableInit() {
    //先销毁表格
    $findAudit.bootstrapTable('destroy');
    $findAudit.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/contractReview/getContractReviewResultList',//请求地址
        method: 'get',//请求方式
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'orderGiftRelationId',
        idField: 'orderGiftRelationId',
        pageSize: 5,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: "[5]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 1,         // 左侧固定列
        fixedRightNumber: 1,    // 右侧固定列
        queryParams: function (params) {
            var temp = {
                pageSize: params.limit,         // 每页数据量
                pageIndex: (params.offset / params.limit) + 1,
                contractId: contractId,
            };
            return temp;
        },
        columns: [
            {title: '主键', field: 'contractReviewId', visible: false},
            {title: '序号', field: 'index', align: 'left', valign: 'middle', width: '80', formatter: indexFormat},//
            {title: '审核不符合类型', field: 'contractReviewTypeName', align: 'left', valign: 'middle',},
            {title: '审核备注', field: 'contractReviewNotes', align: 'left', valign: 'middle'},
            {title: '处理结果', field: 'processResultName', align: 'left', valign: 'middle'},
            {title: '审核时间', field: 'createTm', align: 'left', valign: 'middle'},
            {title: '审核人', field: 'createPeopleName', align: 'left', valign: 'middle'}

        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
                if(result.data.length>0){

                    if(result.data[0].processResultName=='通过'||result.data[0].processResultName=='通过并盖章'){
                        $('#finalResult').attr('src','../../../../images/csd/success-icon.png');
                        $("#judgeProhibit").attr("disabled",true);
                    }else{
                        $('#finalResult').attr('src','../../../../images/csd/fail-icon.png');
                        $("#judgeProhibit").attr("disabled",false);
                    }
                }

            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#giftDetailTable').css({
                minWidth: $('#giftDetailTable').width()
            })
        },
    });
}

function removeModal() {
    location.reload();
}

/**
 *合同详情-编辑Button
 */
$("#editContractBtn").on('click',function (event) {
    $.ajax({
        url: "/csd/customerManager/selectContractDetailVOById",
        async: false,
        type: "post",
        dataType: "json",
        data: {
            contractId: contractId //合同ID
        },
        success: function (data) {
            if (data.code == '000000') {
                var result = data.data;
                $("#contractTypeSelect").val(result.contractType);//合同类型
                $("#contractStatusSelect").val(result.contractStatus);//合同状态
                $('#contact-details').val(result.contactDetails);//联系方式
                $("#contact-name").val(result.contactName);//客户联系人
                $("#customer-email").val(result.customerEmail);//客户邮箱
                var contractStartDate = result.contractStartDate;//合同开始日期
                var contractEndDate = result.contractEndDate;//合同结束日期
                if(!contractStartDate){
                    contractStartDate = '-';
                }
                if(!contractEndDate){
                    contractEndDate = '-';
                }
                membershipStartTm=contractStartDate;
                membershipExpirationTm=contractEndDate;
                if(contractStartDate == '-' && contractEndDate == '-'){
                    $('#startAndEndDate').val('');
                }else{
                    $('#startAndEndDate').val(contractStartDate + ' 至 ' + contractEndDate);
                }

                $('#editContractModal select').selectpicker('refresh');//刷新下拉数据

                /**
                 * 时间  timeData('startAndEndDate','startAndEndDate','editContractForm');
                 // */
                let startTm='',endTm;
                if(membershipStartTm == '-' || membershipStartTm ==''){
                    startTm = moment().startOf('day');
                }else{
                    startTm = membershipStartTm;
                }

                if(membershipExpirationTm=='-' || membershipExpirationTm==''){
                    endTm = moment().add(6, 'day');
                }else{
                    endTm = membershipExpirationTm;
                }
                $('#startAndEndDate').daterangepicker({
                    startDate: startTm,
                    endDate: endTm,
                    autoUpdateInput: false,
                    showDropdowns: true,
                    alwaysShowCalendars: true,
                    ranges: {
                        '本月': [moment().startOf('month'), moment().endOf('month')],
                        '未来一个月': [moment().startOf('day'), moment().add(1, 'month').subtract(1, 'days').endOf('day')],
                        '未来三个月': [moment().startOf('day'), moment().add(3, 'month').subtract(1, 'days').endOf('day')],
                        '未来六个月': [moment().startOf('day'), moment().add(6, 'month').subtract(1, 'days').endOf('day')],
                        '未来一年': [moment().startOf('day'), moment().add(12, 'month').subtract(1, 'days').endOf('day')],
                        '未来三年': [moment().startOf('day'), moment().add(36, 'month').subtract(1, 'days').endOf('day')],
                    },
                    locale: {
                        format: 'YYYY-MM-DD',
                        separator: '至',
                        applyLabel: '确定',
                        cancelLabel: '清空',
                        fromLabel: 'From',
                        toLabel: 'To',
                        customRangeLabel: '自定义日期',
                        weekLabel: 'W',
                        daysOfWeek: ['日', '一', '二', '三', '四', '五', '六'],
                        monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                        firstDay: 1
                    },
                });
                $('#startAndEndDate').on('apply.daterangepicker', function(ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' 至 ' + picker.endDate.format('YYYY-MM-DD'));
                    if($('#editContractForm').data('bootstrapValidator')!=undefined){
                        $('#editContractForm').data('bootstrapValidator')
                            .updateStatus('startAndEndDate', 'NOT_VALIDATED',null)
                            .validateField('startAndEndDate');
                    }
                });

                $('#startAndEndDate').on('cancel.daterangepicker', function(ev, picker) {
                    $(this).val('');
                    if($('#editContractForm').data('bootstrapValidator')!=undefined){
                        $('#editContractForm').data('bootstrapValidator')
                            .updateStatus('startAndEndDate', 'NOT_VALIDATED',null)
                            .validateField('startAndEndDate');
                    }
                });


            }
        }
    })
});

/**
 * 提示信息
 * @param content 提示内容
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

/**
 * 合同详情--编辑保存
 */
function submitContract(){
    var contractTypeSelectText =  $.trim($('#contractTypeSelect option:selected').text());
    var contractTypeText = contractTypeSelectText == "请选择"?"":contractTypeSelectText;

    var contractStatusSelectText =  $.trim($('#contractStatusSelect option:selected').text());
    var contractStatusText = contractStatusSelectText == "请选择"?"":contractStatusSelectText;
    if(contractTypeText ==  $.trim($('#contractType').text())  &&  $('#contact-details').val() == $('#contactDetails').text().split('-').join('')  && $('#startAndEndDate').val() == $('#contractDate').text()
    && $('#contact-name').val() == $('#contactName').text() && $('#customer-email').val() == $('#customerEmail').text() && $('#customer-remark').val() == $('#remark').text()
     && contractStatusText ==  $.trim($('#contractStatus').text())){
        $.alert('暂未修改');
        return;
    }

    var contractType =   $('#contractTypeSelect option:selected').val();//合同类型
    var contractStatus = $('#contractStatusSelect option:selected').val();//合同状态
    var contractStatusText = $('#contractStatusSelect option:selected').text();//合同状态
    var contactDetails = $.trim($('#contact-details').val());//联系方式
    var contactName = $.trim($('#contact-name').val());//客户联系人
    var customerEmail = $('#customer-email').val();//客户邮箱

    var startAndEndDate = $("#startAndEndDate").val().split(' 至 ');
    var contractStartDate = startAndEndDate[0];//合同开始日期
    var contractEndDate = startAndEndDate[1];//合同结束日期
    var remark = $('#customer-remark').val();//备注

    var customerId =  $("#customerId").val();//客户ID
    var orderId =  $('#orderId').val();//订单ID

    if(!remark){
        alert("备注不能为空!");
        return;
    }
    //合同编辑JSON
    var jsonData = {
        contractId,
        customerId,
        orderId,
        "contractType":contractType,
        "contractStatus":contractStatus,
        "contractStatusText":contractStatusText,
        "contactDetails":contactDetails,
        "contactName":contactName,
        "customerEmail":customerEmail,
        "contractStartDate":contractStartDate,
        "contractEndDate":contractEndDate,
        "remark":remark//此字段只往日志表添加
    };

    //合同编辑调用后端
    $.ajax({
        url: '/csd/customerManager/updateCustomerContract',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $('#editContractModal').modal('hide');
                                window.location.reload();
                            }
                        }
                    }
                });
            }else{
                $.alert("保存失败");
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        })
    });
}

/**
 * 合同详情--编辑取消
 */
function clearInp(){
    $('#editContractType').val('');
    $('#editPhone').val('');
    $('#editContactTime').val('');
    $('#editContactUser').val('');
    $('#editContactMail').val('');
}

/**
 * 合同详情--打开关联赢单/跟进
 */
function openFollowUpDetail(){

    if(clueFollowId){//跟进记录ID
        getFollowInfo()//加载跟进记录
    }

    if(opportunityIds){//商机ID
        pageIndex = 1;
        $("#followList").html("");
        getOpportunityInfo(pageIndex,pageSize);//加载商机动态
    }
    $("#followUpDetail").animate({width:"660px",padding:"20px"});
    $(".closeBtn").show();
}

/**
 * 合同详情--关闭关联赢单/跟进
 */
function closeFollowUpDetail(){
    $("#followUpDetail").animate({width:0,padding:0});
    $(".closeBtn").hide();
    $("#followList").html("");
}


//获得跟进信息
function getFollowInfo(){
    $.ajax({
        url: '/contractReview/getFollowRecordDetailById?clueFollowId='+clueFollowId,
        type: 'GET',
        datatype: 'json',
        success: function (data) {
            if(data.code === "000000"){
                let followSource = data.data.followSource;
                $("#personName").html(followSource==6?data.data.personName:data.data.contactName);
                // $("#visitAddress").html(data.data.visitAddress);
                let customerQuality = data.data.customerQuality;
                switch(customerQuality){
                    case 1:
                        customerQuality="优";
                        break;
                    case 2:
                        customerQuality="良";
                        break;
                    case 3:
                        customerQuality="一般";
                        break;
                }
                let followWay = data.data.followWay;
                switch(followWay){
                    case 1:
                        followWay="线上电话";
                        break;
                    case 2:
                        followWay="拜访";
                        break;
                    case 3:
                        followWay="微信";
                        break;
                    case 4:
                        followWay="线下电话";
                        break;
                    case 5:
                        followWay="邮箱";
                        break;
                    case 6:
                        followWay="陪访";
                        break;
                }
                $("#followWay").html('跟进方式-('+followWay+')');
                $("#userPhone").html(followSource==6?data.data.personPhone:data.data.contactInformation);
                $("#followTm").html(data.data.followTm);

                let followPurpose = data.data.followPurpose;
                switch(followPurpose){
                    case '1':
                        followPurpose="产品跟进";
                        break;
                    case '2':
                        followPurpose="过程跟进";
                        break;
                    case '3':
                        followPurpose="商机跟进";
                        break;
                }
                if(data.data.followWay==2){
                    //陪访人
                    $("#accompanyingPerson").html(data.data.accompanyingPerson);
                }else{
                    $("#accompanyingPersonCon").hide()
                }
                if(data.data.followWay!=1){
                    $("#customerQuality").html(customerQuality);
                    $("#nextPlanTime").html(data.data.nextPlanTime);
                    $("#customerIntention").html(data.data.customerIntention?data.data.customerIntention+"%":'');
                    $("#followPurpose").html(followPurpose);
                    $("#clueScore").attr({'data-score':data.data.clueScore});
                    //绘制线索评分星星
                    initScore();
                }else{
                    $("#customerQualityCon").hide();
                    $("#nextPlanTimeCon").hide();
                    $("#customerIntentionCon").hide();
                    $("#followPurposeCon").hide();
                    $("#clueScoreCon").hide();
                    // $("#tagsCon").hide();
                }
                $("#communicationTime").html(data.data.communicationTime?data.data.communicationTime:0);
                $("#followDetail").html(data.data.followDetail?data.data.followDetail:'(无跟进详情)');

            } else {
                promptInfo(data.message);
            }

        },
        error: function (message) {
            promptInfo(message);
        }
    })
}

//获得商机动态信息
function getOpportunityInfo(pageIndex, pageSize) {
    var jsonData = {
        opportunityId:opportunityIds,
        pageIndex: pageIndex,
        pageSize: pageSize,
        sortName: 'createTm',
        sortOrder: 'desc'
    };
    $.ajax({
        url: '/opportunity/opportunityDynamicList',
        type: 'post',
        dataType: 'json',
        async: true,
        data: jsonData,
        success: function (data) {
            if (data.code == '000000') {
                var newData = data.data;
                totalNum = data.totalRecords;
                if (newData.length != 0) {
                    newData.forEach((value) => {
                        var followWay;
                        var opportunityStatus=value.opportunityStatus;
                        var opportunityContent;
                        if(value.operationMode===0){
                            //操作方式为 0-跟进时
                            switch (Number(value.followWay)) {
                                case 1: followWay = '线上电话'; break;
                                case 2: followWay = '拜访'; break;
                                case 3: followWay = '微信'; break;
                                case 4: followWay = '线下电话'; break;
                                case 5: followWay = '邮箱'; break;
                                case 6: followWay = '陪访'; break;
                                default: followWay = '';break;
                            }
                            opportunityContent = value.followDetail;
                        }else if(value.operationMode===1){
                            //操作方式为 1-修改商机状态
                            followWay = '状态修改';
                            switch(opportunityStatus){
                                case '1':
                                    opportunityContent = "初步洽谈";
                                    break;
                                case '2':
                                    opportunityContent = "需求确定";
                                    break;
                                case '3':
                                    opportunityContent = "方案报价";
                                    break;
                                case '4':
                                    opportunityContent = "谈判";
                                    break;
                                case '5':
                                    opportunityContent = "洽谈合同";
                                    break;
                                case '6':
                                    opportunityContent = "赢单";
                                    break;
                                case '7':
                                    opportunityContent = "输单";
                                    break;
                                default:
                                    opportunityContent = "";
                                    break;
                            }
                            opportunityContent = opportunityContent?`将商机状态修改为<span class="label label-warning">${opportunityContent}</span>`:'';
                        }
                        var htmlStr=`<div class="followLi clearFix" >
                                        <div class="followImg">
                                            <span class="headPortrait">
                                                <img src="${value.accessUrl}" alt="">
                                            </span>
                                            <span class="businessStatus">${followWay}</span>
                                        </div>
                                        <div class="followContent">
                                            <div>
                                                <span class="title">跟进人:</span>
                                                <span class="personNames">${value.userName}</span>
                                                <span>/</span>
                                                <span class="time">${new Date(value.createTm).Format("yyyy-MM-dd hh:mm:ss")}</span>
                                            </div>
                                            <div>${opportunityContent}</div>
                                        </div>
                                    </div>`;
                        $("#followList").append(htmlStr);
                    })
                }else{
                    $('#followList').html('<p class="nodata">暂无跟进记录</p>');
                }
            } else{
                promptInfo(data.message);
            }
        },
        error: function (message) {
            promptInfo(message)
        }
    })
}

// 评分插件
function initScore() {
    jQuery(".js-raty").each(function () {
        var a = jQuery(this);
        a.raty({
            starType: "i",
            targetText: a.data("target-text") ? a.data("target-text") : '',
            score: a.data("score") ? a.data("score") : 0,
            number: a.data("number") ? a.data("number") : 5,
            cancel: a.data("cancel") ? a.data("cancel") : !1,
            target: a.data("target") ? a.data("target") : !1,
            targetScore: a.data("target-score") ? a.data("target-score") : !1,
            precision: a.data("precision") ? a.data("precision") : !1,
            cancelOff: a.data("cancel-off") ? a.data("cancel-off") : "mdi mdi-close fa-1-5x text-danger",
            cancelOn: a.data("cancel-on") ? a.data("cancel-on") : "mdi mdi-close fa-1-5x",
            starHalf: a.data("star-half") ? a.data("star-half") : "mdi mdi-star-half fa-1-5x text-warning",
            starOff: a.data("star-off") ? a.data("star-off") : "mdi mdi-star fa-1-5x text-gray",
            starOn: a.data("star-on") ? a.data("star-on") : "mdi mdi-star fa-1-5x text-warning",
            readOnly: true,
        })
    })
}

//查看图片
// function viewBtn(){
//     mySwiper();
//     $('#visitImg').modal('show');
// }

function mySwiper() {
    var pageNumber;
    new Swiper('.swiper-container', {
        observer:true,
        observeParents: true,
        spaceBetween: 30,
        effect: 'fade',
        loop: true,
        // autoplay: true,
        delay: 300,
        pagination: {
            el: '.swiper-pagination',
            clickable: true,
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        on: {
            slideChangeTransitionStart: function () {
                var index = Number(this.activeIndex);
                console.log(index);
                if (index == 4) {
                    index = 1
                }
                if (index == 0) {
                    index = 3;
                }
                pageNumber = index;
            }
        },
    });
}